package com.weiyi.portal.modules.ums.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.weiyi.common.common.exception.ApiException;
import com.weiyi.common.common.exception.Asserts;
import com.weiyi.portal.domain.MemberDetails;
import com.weiyi.portal.dto.UmsUserInfoDTO;
import com.weiyi.portal.modules.pms.service.PmsProductService;
import com.weiyi.portal.modules.ums.model.UmsFriendsRelation;
import com.weiyi.portal.modules.ums.model.UmsMember;
import com.weiyi.portal.modules.ums.mapper.UmsMemberMapper;
import com.weiyi.portal.modules.ums.model.UmsNews;
import com.weiyi.portal.modules.ums.service.UmsFriendsRelationService;
import com.weiyi.portal.modules.ums.service.UmsMemberCacheService;
import com.weiyi.portal.modules.ums.service.UmsMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weiyi.portal.modules.ums.service.UmsNewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author PZC
 * @since 2022-10-13
 */
@Service
public class UmsMemberServiceImpl extends ServiceImpl<UmsMemberMapper, UmsMember> implements UmsMemberService {
    @Autowired
    UmsMemberCacheService memberCacheService;
    @Autowired
    UmsMemberService umsMemberService;
    @Autowired
    PmsProductService pmsProductService;
    @Autowired
    UmsNewsService umsNewsService;
    @Autowired
    UmsFriendsRelationService umsFriendsRelationService;

    /**
     * 根据用户名从cache或者磁盘中获取用户信息
     * @param username
     * @return
     */
    public UmsMember getAdminByUsername(String username) {
        UmsMember user = memberCacheService.getUser(username);

        if(user!=null) return  user;
        QueryWrapper<UmsMember> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UmsMember::getUsername,username);
        List<UmsMember> adminList = list(wrapper);
        if (adminList != null && adminList.size() > 0) {
            user = adminList.get(0);
            memberCacheService.setUser(user);
            return user;
        }
        return null;
    }


    public MemberDetails loadUserByUserName(String username) {
        UmsMember umsMember = getAdminByUsername(username);
        if(umsMember!=null){
            return new MemberDetails(umsMember);
        }
        throw  new ApiException("用户名或密码错误!");
    }

    @Override
    public UmsMember login(String userName, String passWord) {

        UmsMember umsMember=null;

        try {
            MemberDetails user = loadUserByUserName(userName);

            umsMember = user.getUmsMember();

            if (!BCrypt.checkpw(passWord, umsMember.getPassword())) {
                Asserts.fail("密码错误");
            }

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            if (!user.isEnabled()) {
                Asserts.fail("用户被禁用");
            }
        }catch (Exception e){
                Asserts.fail("登录异常:"+e.getMessage());
        }

        return umsMember;
    }


    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public UmsMember register(UmsMember user){
        System.out.println(user.getUsername());
        user.setFollowNum(0);
        user.setFollowNum(0);
        user.setCreateTime(new Date());
        user.setStatus(1);

        QueryWrapper<UmsMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UmsMember::getUsername, user.getUsername());
        List<UmsMember> umsMembers = list(queryWrapper);
        if(umsMembers.size()>0){
            return null;
        }
        String hashpw = BCrypt.hashpw(user.getPassword());
        user.setPassword(hashpw);
        save(user);
        return user;
    }

    @Override
    public UmsUserInfoDTO getUserHomeInfo(Long id) {
        UmsUserInfoDTO umsUserInfoDTOS=new UmsUserInfoDTO();

        QueryWrapper<UmsMember>queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(UmsMember::getId, id);
        UmsMember member = umsMemberService.getOne(queryWrapper);

        QueryWrapper<UmsNews>queryWrapper1=new QueryWrapper<>();
        queryWrapper1.lambda().eq(UmsNews::getAuthorId, id);
        List<UmsNews> news = umsNewsService.list(queryWrapper1);

        umsUserInfoDTOS.setUmsMember(member);
        umsUserInfoDTOS.setNews(news);
        return umsUserInfoDTOS;
    }

    @Override
    public void updateFansFollowNum(String username, String type, String op) {
        UpdateWrapper<UmsMember>updateWrapper=new UpdateWrapper<>();
        updateWrapper.setSql(type + "=" + type + op + "1").lambda().eq(UmsMember::getUsername, username);
        umsMemberService.update(updateWrapper);
    }

    /**
     * 根据用户id查询其关注的用户信息
     * @param id
     * @return
     */
    @Override
    public List<UmsMember> getFollowById(Integer id) {
        QueryWrapper<UmsFriendsRelation>queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(UmsFriendsRelation::getFromUser, id);
        Map<String, Object> map = umsFriendsRelationService.getMap(queryWrapper);
        List<String>followNames= (List<String>) map.get("toUser");

        List<UmsMember>followDetail=new ArrayList<>();
        for(String name:followNames){
            followDetail.add(getAdminByUsername(name));
        }

        return followDetail;
    }


    /**
     * 根据用户id查询其关注的用户信息
     * @param id
     * @return
     */
    @Override
    public List<UmsMember> getFansById(Integer id) {
        QueryWrapper<UmsFriendsRelation>queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(UmsFriendsRelation::getToUser, id);
        Map<String, Object> map = umsFriendsRelationService.getMap(queryWrapper);
        List<String>fansNames= (List<String>) map.get("fromeUser");

        List<UmsMember>fansDetail=new ArrayList<>();
        for(String name:fansNames){
            fansDetail.add(getAdminByUsername(name));
        }

        return fansDetail;
    }
}
